const express = require("express");
const db = require("../module/DBHeler");
const moment=require("moment");
const ApiRouter = express.Router();

//获取
ApiRouter.get("/select",async(req,res)=>{
    //1.准备sql语句的参数
    let params=[req.query.username]
    //2.准备sql语句
    let sql = "SELECT *FROM `ouserlist` WHERE  `u_name`=? ";
    //3.执行sql语句
    try {
        let result = await db.exec(sql, params);
        delete (result[0].upwd);//删除对象的属性
        console.log(result);
        let isLogin = result && result.length >= 1;
        res.json({
            msg: isLogin ? 1 :2
        })

    } catch (error) {
        res.json({ msg: isLogin ? 1 :2 })
    }
})



//登陆
ApiRouter.post("/login", async (req, res) => {

    //1.准备sql语句的参数
    let params = [
        req.body.username,
        req.body.pwd
    ]
    //2.准备sql语句
    let sql = "SELECT *FROM `ouserlist` WHERE `u_status`=1 AND `u_name`=? AND `u_pwd`=?";
    //3.执行sql语句
    try {
        let result = await db.exec(sql, params);
        delete (result[0].u_pwd);//删除对象的属性
        let isLogin = result && result.length >= 1;
        res.json({
            msg: isLogin ? "登录成功" : "登录失败",
            code: isLogin ? 200 : -200,
            data: isLogin ? result[0] : {}
        })

    } catch (error) {
        res.json({ msg: "登录失败", error })
    }
})

//注册
ApiRouter.post("/reg", async (req, res) => {

    //1.接受前端的参数
    let params = [
        req.body.username,
        req.body.pwd,
        req.body.phone,
        //获取当前服务器的事件
        moment().format("YYYY-MM-DD hh:mm:ss")
    ]
    //2.准备sql语句
    let sql = "INSERT INTO `ouserlist` (`u_name`,`u_pwd`,`u_phone`,`u_created`)";
    sql += "VALUES(?,?,?,?);";
    //3.执行sql语句
    try {
        let result = await db.exec(sql, params);
        const isReg = result && result.affectedRows >= 1;
        res.json({
            msg: isReg ? "注册成功!" : "注册失败!",
            code: isReg ? 200 : -200
        })

    } catch (error) {
        res.json({ msg: "注册失败!", error })
    }
})

module.exports = { ApiRouter }




